﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO.IsolatedStorage;
using System.Net;
using System.Threading.Tasks;
using System.Windows;
using SC2TV.Tools;

namespace SC2TV.ViewModel
{
    public class MainViewModel : BaseViewModel
    {
        public string Login { get; set; }
        public string Password { get; set; }

        internal async Task<HttpStatusCode> Load()
        {
            try
            {
                var requester = new Requester("http://sc2tv.ru");
                var response = await requester.Post(new Collection<KeyValuePair<string, string>>
                {
                    new KeyValuePair<string, string>("name", Login),
                    new KeyValuePair<string, string>("pass", Password),
                    new KeyValuePair<string, string>("form_id","user_login_block")
                });
                if (response.Cookies.Count > 0)
                {
                    IsolatedStorageSettings.ApplicationSettings.Add("bb_lastactivity", response.Cookies["bb_lastactivity"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("bb_lastvisit", response.Cookies["bb_lastvisit"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("bb_password", response.Cookies["bb_sessionhash"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("bb_sessionhash", response.Cookies["bb_lastactivity"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("bb_userid", response.Cookies["bb_userid"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("drupal_uid", response.Cookies["drupal_uid"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("drupal_user", response.Cookies["drupal_user"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("SESS4a29996287c6a61196a9cfc443f0fdb3", response.Cookies["SESS4a29996287c6a61196a9cfc443f0fdb3"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("nocache", response.Cookies["nocache"].Value);
                    IsolatedStorageSettings.ApplicationSettings.Add("clientID", Guid.NewGuid());
                }
                else
                {
                    MessageBox.Show("Неверное имя пользователя/пароль");
                    return new HttpStatusCode();
                }
                return response.StatusCode;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return new HttpStatusCode();
            }


        }
    }
}
